<?php

class Rider_model extends CI_Model
{
	public function __construct()
	{
		$this->load->database();
		$this->load->helper('date');
	}

	public function insert_rider($password, $phone_number)
	{
		$data = array(
			'passwd' => substr(hash("sha256", $password),32),
			'phone_number' => $phone_number
		);
		if ($this->test_uniq('rider', 'phone_number', $phone_number)){
			$this->db->insert('rider', $data);
			return $this->db->insert_id();
		}else{
			return -1;
		}
	}

	public function test_uniq($table, $column, $data)
	{
		$result = $this->db->get_where($table, array($column => $data))->result();
		if(empty($result)){
			return true;
		}else{
			return false;
		}
	}

	public function view_order_detail($id)
	{
		$sql = "SELECT orders.id id, comfirm_time, address.addr dst_addr, address.rname dst_name, address.phone_number dst_phone, 
				merchant.mname src_name, merchant.address src_addr, merchant.phone_number src_phone
				FROM orders, address, merchant
				WHERE orders.id = $id AND orders.mid = merchant.id AND address.id = orders.addrid";
		$result = $this->db->query($sql)->row();
		if($result){
			return $result;
		}else{
			return false;
		}
	}

	public function get_my_unfinished_order($id)
	{
		$sql = "SELECT orders.id id, comfirm_time, address.addr dst_addr, address.rname dst_name, address.phone_number dst_phone, 
				merchant.mname src_name, merchant.address src_addr, merchant.phone_number src_phone
				FROM orders, address, merchant
				WHERE orders.arrival_time IS NULL AND orders.rid = $id AND orders.mid = merchant.id AND address.id = orders.addrid";
		$result = $this->db->query($sql)->result();
		if($result){
			return $result;
		}else{
			return false;
		}
	}

	public function get_unreceived_order()
	{
		$sql = "SELECT orders.id id, comfirm_time, address.addr dst_addr, 
				merchant.mname src_name, merchant.address src_addr
				FROM orders, address, merchant
				WHERE orders.rid IS NULL AND orders.mid = merchant.id AND address.id = orders.addrid";
		$result = $this->db->query($sql)->result();
		if($result){
			return $result;
		}else{
			return false;
		}
	}

	public function receive_order($rid, $oid)
	{
		$this->db->set('rid', $rid);
		$this->db->where('id', $oid);
		$result = $this->db->update('orders');
		if($result){
			return true;
		}else{
			return false;
		}
	}

	public function finish_order($oid)
	{
		$time = date('Y-m-d H:i:s', now('Asia/Shanghai'));
		$this->db->set('arrival_time', $time);
		$this->db->where('id', $oid);
		$result = $this->db->update('orders');
		if($result){
			return $time;
		}else{
			return false;
		}
	}
}
